function [TS,vol_t, mean_t] = scoreTS(R, HL, seed, min_max)
% scoreTS: Score a TS structure
% TS = scoreTS(R, HL, cap)  Turn raw TS data into z-scores
% with optional min and max caps.  EWMA scoring using a halflife.
% Examples:
%    TS = scoreTS(R, halflife);
%    TS = scoreTS(R, halflife, seed, [-3,3]);
%

if nargin < 4, cap = [-Inf,Inf]; end
if nargin < 3, seed = HL; end

N = length(R.dates);
gamma = 0.5^(1/HL);
mean_t = mean(R.data(1:seed,:));
vol_t = std(R.data(1:seed,:));
TS = buildTS([], R.header, R.dates); 

TS.data(1:seed,:) = (R.data(1:seed,:)-repmat(mean_t,seed,1))./repmat(vol_t,seed,1);

%score the time series
for i = (seed+1):N
    mean_t = mean_t*gamma + R.data(i,:)*(1-gamma);
    vol_t = sqrt((vol_t.^2)*gamma + ((R.data(i,:)-mean_t).^2)*(1-gamma));
    TS.data(i,:) = (R.data(i,:)-mean_t)./vol_t;
end

TS.data = max(cap(1),min(cap(2),TS.data));

end